/**
 * 检查是否登录接口
 */

//引入Q模块
var Q = require('q');

//引入公共函数
var util = require('../../util');

//checkLogin入口函数
var index = function(getData, postData, config, _redis, db) {
	var deferred = Q.defer();
	if(postData.storeId == '') {
		deferred.reject('-0004');
	}
	else {
		db.select('storeInfo', {}).then(function(storeInfo) {
			util.array2obj(storeInfo).then(function(storeData) {
				if(postData.identity == 'service') {
					let noReceiveFunLogs = [];
					let noDoneOrders = [];
					db.select('noReceiveFunLogs').then(function(data) {
						//获取未读服务通知列表
						noReceiveFunLogs = data;
						return db.removeAll('noReceiveFunLogs', {});
					}, function() {
						//获取未读服务通知列表失败
						deferred.reject('-0100');
					}).then(function() {
						return db.select('storeOrder', {
							$or: [
								{payMode: 'wxPay', orderDone: false, userPayed: true}, 
								{payMode: 'cashPay', orderDone: false, userPayed: false}
							]
						});
					}, function() {
						//删除未读服务通知列表失败
						deferred.reject('-0101');
					}).then(function(_noDoneOrders) {
						noDoneOrders = _noDoneOrders;
						return db.select('chatListLogs', {
							serviceReceive: false
						});
					}, function() {
						//查询未完成订单失败
						deferred.reject('-0102');
					}).then(function(unreadMsg) {
						if(unreadMsg.length == 0) {
							deferred.resolve({
								storeData: storeData,
								unreadMsg: [],
								noReceiveFunLogs: noReceiveFunLogs || [],
								noDoneOrders: noDoneOrders || []
							});
						}
						else {
							db.updateAll('chatListLogs', {
								serviceReceive: false
							}, {
								serviceReceive: true
							}).then(function() {
								deferred.resolve({
									storeData: storeData,
									unreadMsg: unreadMsg || [],
									noReceiveFunLogs: noReceiveFunLogs || [],
									noDoneOrders: noDoneOrders || []
								});
							}, function() {
								deferred.reject('-0079');
							});
						}
					}, function() {
						deferred.reject('0078');
					});
				}
				else {
					deferred.resolve({
						storeData: storeData
					});
				}
			}, function() {
				deferred.reject('-0040');
			});
		}, function() {
			deferred.reject('-0040');
		});
	}
	return deferred.promise;
}

//暴露接口
module.exports = {
	index: index
};